/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.opengoofy.index12306.framework.starter.designpattern.chain;





import org.opengoofy.index12306.framework.starter.bases.ApplicationContextHolder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.util.CollectionUtils;
import org.springframework.core.Ordered;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 抽象责任链上下文类，用于管理和执行责任链组件。
 * 该类实现了CommandLineRunner接口，可以在Spring Boot应用启动时执行一些初始化操作。
 */
public final class AbstractChainContext<T> implements CommandLineRunner {

    // 存储责任链处理器组件的容器，以责任链标识为键，处理器列表为值
    private final Map<String, List<AbstractChainHandler>> abstractChainHandlerContainer = new HashMap<>();

    /**
     * 责任链组件执行方法。
     * 根据提供的标识，找到对应的责任链处理器列表并依次执行处理方法。
     *
     * @param mark         责任链组件标识
     * @param requestParam 请求参数
     */
    public void handler(String mark, T requestParam) {
        // 根据标识获取责任链处理器列表
        List<AbstractChainHandler> abstractChainHandlers = abstractChainHandlerContainer.get(mark);
        // 如果处理器列表为空或不存在，抛出运行时异常
        if (CollectionUtils.isEmpty(abstractChainHandlers)) {
            throw new RuntimeException(String.format("[%s] Chain of Responsibility ID is undefined.", mark));
        }
        // 遍历处理器列表，依次调用处理方法
        abstractChainHandlers.forEach(each -> each.handler(requestParam));
    }

    /**
     * 实现CommandLineRunner接口的run方法，在Spring Boot应用启动时执行。
     * 用于初始化责任链处理器组件，并将它们按照顺序存储到容器中。
     *
     * @param args 命令行参数
     * @throws Exception 如果初始化过程中发生异常
     */
    @Override
    public void run(String... args) throws Exception {
        // 获取Spring容器中所有类型为AbstractChainHandler的Bean
        Map<String, AbstractChainHandler> chainFilterMap = ApplicationContextHolder
                .getBeansOfType(AbstractChainHandler.class);
        // 遍历Bean，进行初始化和排序
        chainFilterMap.forEach((beanName, bean) -> {
            // 获取当前标识下的处理器列表
            List<AbstractChainHandler> abstractChainHandlers = abstractChainHandlerContainer.get(bean.mark());
            // 如果列表不存在，则创建一个新的列表
            if (CollectionUtils.isEmpty(abstractChainHandlers)) {
                abstractChainHandlers = new ArrayList<>();
            }
            // 将处理器添加到列表中
            abstractChainHandlers.add(bean);
            // 对处理器列表进行排序，根据Ordered接口的getOrder方法返回值排序
            List<AbstractChainHandler> actualAbstractChainHandlers = abstractChainHandlers.stream()
                    .sorted(Comparator.comparing(Ordered::getOrder))
                    .collect(Collectors.toList());
            // 将排序后的处理器列表存回容器
            abstractChainHandlerContainer.put(bean.mark(), actualAbstractChainHandlers);
        });
    }
}
